package com.scrm.exam.utils;

import org.springframework.web.util.ContentCachingRequestWrapper;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;

/**
 * IO 工具类
 *
 */
public class IOUtils extends org.apache.commons.io.IOUtils {
	// Suppresses default constructor, ensuring non-instantiability.
	private IOUtils() {
	}

	public static byte[] requestBodyArray(HttpServletRequest request) {
		if (ContentCachingRequestWrapper.class.isAssignableFrom(request.getClass())) {
			return ((ContentCachingRequestWrapper) (request)).getContentAsByteArray();
		}

		try {
			return toByteArray(request.getInputStream());
		} catch (IOException e) {
		}

		return new byte[] {};
	}

	public static String requestBody(HttpServletRequest request) {
		byte[] bytes = requestBodyArray(request);
		if (bytes.length > 0) {
			if (ContentCachingRequestWrapper.class.isAssignableFrom(request.getClass())) {
				ContentCachingRequestWrapper requestWrapper = ((ContentCachingRequestWrapper) (request));
				try {
					return new String(bytes, requestWrapper.getCharacterEncoding());
				} catch (UnsupportedEncodingException e) {
				}
			}

			return new String(bytes, StandardCharsets.UTF_8);
		}

		return "";
	}

}
